/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: QuotationDome
 * Author:   Administrator
 * Date:     2019/5/15 13:25
 * Description: 报价测试
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.sunlord.controller;

import OThinker.Common.Data.BoolMatchValue;
import OThinker.Common.Data.Database.ICommand;
import OThinker.Common.DotNetToJavaStringHelper;
import OThinker.Common.Organization.Models.OrganizationUnit;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.MvcSheet.Data.MvcDataItemTable;
import OThinker.H3.Controller.MvcSheet.Data.MvcListItem;
import OThinker.H3.Controller.RestfulApi.Entity.RestfulApiResult;
import OThinker.H3.Controller.ViewModels.DataItem;
import OThinker.H3.Entity.Data.Attachment.Attachment;
import OThinker.H3.Entity.Data.Attachment.AttachmentHeader;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.DataModel.BizObjectSchema;
import OThinker.H3.Entity.DataModel.IBizObjectManager;
import OThinker.H3.Entity.Instance.Data.IInstanceDataItem;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Instance.Data.InstanceDataItem;
import OThinker.H3.Entity.Instance.Data.ItemValueTable;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.enums.AttachmentOpenMethod;
import com.h3bpm.base.util.AppConfig;
import com.h3bpm.base.util.AppUtility;
import com.sunlord.dto.Bj;
import com.sunlord.dto.Bjsb;
import com.sunlord.workflow.WorkflowNewParam;
import com.sunlord.workflow.WorkflowNewRet;
import data.DataRowCollection;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 〈一句话功能简述〉<br> 
 * 〈报价测试〉
 *
 * @author Administrator
 * @create 2019/5/15
 * @since 1.0.0
 */
@RestController
@RequestMapping("/quotation")
public class QuotationDome {

    private static final BPMServiceImpl bpmService = new BPMServiceImpl();

    /**
     *  测试 报价发起流程
     * @param objectId  申请流程实例id
     * @param workflowCode 审批流程模板code
     * @return
     */
    @RequestMapping("/test")
    public WorkflowNewRet quotationDome(String objectId,String workflowCode){
        try {
            //查询申请流程实例数据的sql
            String mbsql =  "SELECT bj from i_baojia where ObjectID = '"+objectId+"'";
            //查询申请流程子表数据sql
            String sbsql = "SELECT b.ParentObjectID,b.ObjectID,b.ppbm,b.txsh,b.khmc,b.bm,b.mc,b.khbm,b.num,b.pric,b.shtg,b.ppmc,b.pmbm,b.pmmc,b.ParentIndex from  i_bjxq b  " +
                    "where b.ParentObjectID ='"+objectId+"'";
            //获取sql 执行控制器
            ICommand iCommand = AppUtility.getEngine().getEngineConfig().getCommandFactory().CreateCommand();
            //获取到流程数据信息
            DataRowCollection newsTableRows = iCommand.ExecuteDataTable(mbsql).getRows();
            //获取到申请流程数据项信息
            String bjstring = newsTableRows.get(0).getString("bj");
            //新开审批流程实例主表
            Bj bj=  null;
            //获取申请流程实例子表信息
            newsTableRows = iCommand.ExecuteDataTable(sbsql).getRows();
            //新开审批流程实例子表
            Bjsb bjSb = null;
            // 审批流程的list
            List<Bj> bjlist = new ArrayList<>();
            //审批流程子表与审批人映射map
            Map<String, List<Bjsb>> map = new HashMap<>(16);
            // 循环子表 根据 审批人 objectId 分组
            for (int i = 0; i < newsTableRows.size(); i++) {
                bjSb = new Bjsb();
                //编码
                bjSb.setBm(newsTableRows.get(i).getString("bm"));
                //名称
                bjSb.setMc(newsTableRows.get(i).getString("mc"));
                //品牌编码
                bjSb.setPpbm(newsTableRows.get(i).getString("ppbm"));
                //品牌名称
                bjSb.setPpmc(newsTableRows.get(i).getString("ppmc"));
                //单价
                bjSb.setPric(newsTableRows.get(i).getString("pric"));
                //数量
                bjSb.setNum(newsTableRows.get(i).getString("num"));

                //如果map 里 没有审批人，新建子表list， 并给审批流程主表赋值
                if (!map.containsKey(newsTableRows.get(i).getString("txsh"))){
                    map.put(newsTableRows.get(i).getString("txsh"),new ArrayList<>());
                    bj = new Bj();
                    bj.setBj(bjstring);
                    bj.setKhbm(newsTableRows.get(i).getString("khbm"));
                    bj.setKhmc(newsTableRows.get(i).getString("khmc"));
                    bj.setPmbm(newsTableRows.get(i).getString("pmbm"));
                    bj.setPmmc(newsTableRows.get(i).getString("pmmc"));
                    bj.setTxsh(newsTableRows.get(i).getString("txsh"));

                    bjlist.add(bj);
                }
                map.get(newsTableRows.get(i).getString("txsh")).add(bjSb);
            }
            //流程数据封装
            WorkflowNewParam workflowParam = null;
            //流程发起返回结果
            WorkflowNewRet result = null;
            if(!bjlist.isEmpty()){
                JSONObject mbs = null;
                for(Bj b: bjlist){
                    mbs = JSONObject.parseObject(JSON.toJSONString(b));
                    mbs.put("bjxq1",JSON.parseArray(JSON.toJSONString(map.get(b.getTxsh()))));
                    workflowParam = new WorkflowNewParam(workflowCode,b.getPmbm(), "true", mbs.toJSONString());
                    //发起流程
                    result = this.exworkflow(workflowParam);

                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public WorkflowNewRet exworkflow( WorkflowNewParam param){
        try {

            BPMServiceResult result = bpmService.StartWorkflowNew("H3", "Authine", param.getWorkflowCode(), param.getUserCode(), param.getFinishStart(), param.getParamValues());
            return setRet(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置返回值
     * @param result BPMServiceResult
     * @return WorkflowNewRet
     */
    private WorkflowNewRet setRet(BPMServiceResult result) {
        WorkflowNewRet ret = new WorkflowNewRet();
        ret.setSuccess(result.isSuccess());
        ret.setMessage(result.getMessage());
        ret.setInstanceID(result.getInstanceId());
        ret.setWorkItemID(result.getWorkItemId());
        ret.setWorkItemUrl(result.getWorkItemUrl());
        return ret;
    }



    @RequestMapping("TestAttrCopy")
    public RestfulApiResult TestAttrCopy(String instanceId) throws Exception {


        InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);


        IInstanceDataItem ymagatt = instanceData.getItem("YMAGATT");

        Object value = ymagatt.getValue();
        String schemaCode = instanceData.getSchemaCode();
        String objectID = instanceData.getBizObject().getObjectID();
        String DataField = "YMAGATT";
        BoolMatchValue LastVersion = BoolMatchValue.False;
        String FileName = null;

        IBizObjectManager manager = AppUtility.getEngine().getBizObjectManager();

        List<AttachmentHeader> headers = manager.QueryAttachment(schemaCode, objectID, DataField, LastVersion, FileName);

        Attachment attachment = manager.GetSingleAttachment(User.AdministratorID, schemaCode, objectID, DataField, headers.get(0).getFileName());

        byte[] content = attachment.getContent();


        return  null;
    }


    @RequestMapping("TestAttrCopya")
    public RestfulApiResult TestAttrCopya(String instanceId, @RequestParam(value="attaFields[]") String[] attaFields) throws Exception {

        if (attaFields == null || attaFields.length==0){
            return RestfulApiResult.fail("数据项编码不能为空");
        }

        if (instanceId == null || instanceId.trim().length() == 0 ){
            return RestfulApiResult.fail("实例id不合法");
        }

        InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
        Map<String,Object> dataItems  = new HashMap<>();

        for (String field : attaFields){

            if (field == null || field.trim().length()==0 ){
                continue;
            }
            dataItems.put(field,getSelfAttaDataToCopy(instanceData,field));


        }

        return  RestfulApiResult.success(dataItems);
    }



    public List<MvcListItem> getSelfAttaDataToCopy(InstanceData instanceData,String DataField) throws Exception {
        IBizObjectManager manager = AppUtility.getEngine().getBizObjectManager();
        String schemaCode = instanceData.getSchemaCode();
        String objectID = instanceData.getBizObject().getObjectID();
        List<AttachmentHeader> headers = manager.QueryAttachment(schemaCode,objectID, DataField, BoolMatchValue.True, null);

        List<MvcListItem> listItems = new ArrayList();
        Attachment attachment ;
        Attachment newAtta ;
        String newAttaObjectID,url;
        for (AttachmentHeader header :headers){
            attachment = manager.GetSingleAttachment(User.AdministratorID, schemaCode, objectID, DataField, header.getFileName());

            newAtta = new Attachment();
            newAtta.setObjectID( UUID.randomUUID().toString());
            newAtta.setContent(attachment.getContent());
            newAtta.setContentType(attachment.getContentType());
            newAtta.setCreatedBy(User.AdministratorID);
            newAtta.setCreatedTime(new Date());
            newAtta.setFileName(attachment.getFileName());
            newAtta.setLastVersion(true);
            newAtta.setModifiedTime(new Date());
            // 流程编码
            newAtta.setBizObjectSchemaCode(schemaCode);
            newAtta.setContentLength(attachment.getContentLength());
            // 流程id
//            attachment.setBizObjectId(objectID);
//            attachment.setDataField(DataField);
            newAttaObjectID = manager.AddAttachment(newAtta);
            url = DotNetToJavaStringHelper.isNullOrEmpty(header.getDownloadUrl()) ? AppConfig.GetReadAttachmentUrl(null,false, schemaCode, null, newAttaObjectID, AttachmentOpenMethod.Download) : header.getDownloadUrl();
            listItems.add(new MvcListItem(newAttaObjectID, newAtta.getFileName(), url, newAtta.getContentLength(), newAtta.getContentType()));

        }
        return  listItems;
    }

    public Map<String, Object> getSonTableAttaDataToCopy(InstanceData instanceData,String DataField) throws Exception {
        IBizObjectManager manager = AppUtility.getEngine().getBizObjectManager();
        String schemaCode = instanceData.getSchemaCode();
        Object sonTb = instanceData.getBizObject().GetValue(DataField.split(".")[0]);

        BizObject[] sonObjs = (BizObject[])((sonTb instanceof BizObject[]) ? sonTb : null);



        if (sonObjs == null || sonObjs.length==0){
            return  null;
        }
        Map<String, Object> map = new HashMap<>(sonObjs.length);
        List<AttachmentHeader> headers ;
        List<MvcListItem> listItems;
        String objectID;
        Attachment attachment ;
        Attachment newAtta ;
        String newAttaObjectID,url;
        for (BizObject biz : sonObjs){
            objectID = biz.getObjectID();
            headers = manager.QueryAttachment(schemaCode,objectID, DataField, BoolMatchValue.True, null);
            listItems = new ArrayList();
            for (AttachmentHeader header :headers){
                attachment = manager.GetSingleAttachment(User.AdministratorID, schemaCode, objectID, DataField, header.getFileName());

                newAtta = new Attachment();
                newAtta.setObjectID( UUID.randomUUID().toString());
                newAtta.setContent(attachment.getContent());
                newAtta.setContentType(attachment.getContentType());
                newAtta.setCreatedBy(User.AdministratorID);
                newAtta.setCreatedTime(new Date());
                newAtta.setFileName(attachment.getFileName());
                newAtta.setLastVersion(true);
                newAtta.setModifiedTime(new Date());
                // 流程编码
                newAtta.setBizObjectSchemaCode(schemaCode);
                newAtta.setContentLength(attachment.getContentLength());
                // 流程id
//            attachment.setBizObjectId(objectID);
//            attachment.setDataField(DataField);
                newAttaObjectID = manager.AddAttachment(attachment);
                url = DotNetToJavaStringHelper.isNullOrEmpty(header.getDownloadUrl()) ? AppConfig.GetReadAttachmentUrl(null,false, schemaCode, null, newAttaObjectID, AttachmentOpenMethod.Download) : header.getDownloadUrl();
                listItems.add(new MvcListItem(newAttaObjectID, attachment.getFileName(), url, attachment.getContentLength(), attachment.getContentType()));

            }

            map.put(objectID,listItems);

        }
        return  map;
    }


    public void testcopybizobject () throws Exception {


    }

    @RequestMapping("mytest")
    public WorkflowNewRet mytest(){
        WorkflowNewParam workflowParam =  new WorkflowNewParam("myworkflow",User.AdministratorAlias, "true", new JSONObject().toString());

        WorkflowNewRet exworkflow = this.exworkflow(workflowParam);



        return exworkflow;
    }



    @RequestMapping("mytest1")
    public long mytest1() throws Exception {

        BizObjectSchema schema = AppUtility.getEngine().getBizObjectManager().GetPublishedSchema(
                "DemoWS");

        BizObject bo = new BizObject(AppUtility.getEngine().getOrganization(),
                AppUtility.getEngine().getMetadataRepository(),
                AppUtility.getEngine(). getBizObjectManager(),
                AppUtility.getEngine().getBizBus(),
                schema,
                User.AdministratorID,
                OrganizationUnit.DefaultRootID);

        bo.setItem("displayName","test1111");
        bo.Create(null);
        return  new Date().getTime();
    }

}